<!DOCTYPE HTML>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
		<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
		<title></title>
		<link rel="stylesheet" type="text/css" href="../../css/api.css" />
		<link rel="stylesheet" type="text/css" href="../../css/style.css" />
		<link rel="stylesheet" type="text/css" href="../../css/btnplus.css" />
		<style type="text/css">
			html,body { background: #FCFDFE; }
			/*实名验证*/
			.upload_info{ padding: 0 0.50rem 0.40rem;}
			.upload_info h2{display:block; color: #121212; font-size: 0.60rem; line-height: 1.0rem;}
			.upload_img{ padding-top:0.35rem;}
			.upload_img label,.company_name label{ display:block; font-size: 0.39rem; color: #121212; line-height: 0.80rem;}
			.upload_img label i{ color: #ff0000;}
			.upload_img div{ margin-top: 0.20rem;}
			.upload_img a{ display:block; position: relative; border: 1px #ccc solid; padding: 0.10rem; background-color: #f6f6f6; overflow: hidden;}
			.upload_img .img{ width:100%; height: 3.84rem; border-radius: 0.08rem; object-fit: cover;}
			.upload_img a input{ position:absolute; right: 0; top: 0; font-size: 3.0rem; opacity: 0; z-index: 2; background-color: transparent;}
			.upload_img span{ position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: 1; padding-top: 1.10rem;}
			.upload_img span img{ margin: 0 auto; width: 1.15rem;}
			.upload_img p{ text-align: center; font-size: 0.30rem; color: #121212; line-height: 1.0rem;}
			.company_name{ padding-top: 0.35rem;}
			.company_name label{ line-height:0.60rem; padding-top: 0.10rem;}
			.company_name input{ display:block; border: 0; width: 100%; font-size: 0.28rem; padding: 0.25rem 0; color: #666; background: url(../images/img_12.png) no-repeat right center; background-size: 0.14rem auto;}
			.check{ font-size: 0.28rem; color: #121212; line-height: 1.0rem; margin-bottom: 0.25rem;}
			.check a{ display:inline; color: #3262F1;}
			.check p{ position: relative; padding-left: 0.40rem;}
			.check p input{ position: absolute; left: 0; top: 0.35rem; width: 0.30rem; height: 0.30rem; box-sizing: border-box;}

		</style>
	</head>
	<body>
		<!--完善信息start-->
		<div class="upload_info">
			<h2>完善信息</h2>
			<ul>
			  <li class="upload_img">
					<label>身份证照片上传<i>*</i></label>
					<div>
					  <a href="javascript:;" title="">
						<img src="../../image/img_06.png" id="cardIDthumb1" class="img" />
						<span tapmode onclick="selpic(1);">
						  <img src="../../image/img_11.png" alt="" />
								<p>正面照</p>
							</span>
						</a>
					</div>
					<div>
					  <a href="javascript:;" title="">
						<img src="../../image/img_07.png" id="cardIDthumb2" class="img" />
						<span tapmode onclick="selpic(2);">
						  <img src="../../image/img_11.png" alt="" />
								<p>背面照</p>
							</span>
						</a>
					</div>
					<div>
					  <a href="javascript:;" title="">
						<img src="../../image/img_08.png" id="cardIDthumb3" class="img" />
						<span tapmode onclick="selpic(3);">
						  <img src="../../image/img_11.png" alt="" />
								<p>手持身份证照</p>
							</span>
						</a>
					</div>
				</li>
				<li class="company_name header_01">
					<label>姓名</label>
					<input type="text" value="" id="realname" placeholder="请填写姓名" />
				</li>
				<li class="company_name header_01">
					<label>身份证号码</label>
					<input type="text" value="" id="idcard" placeholder="请填写身份证号码" />
				</li>
				<li style="margin-top:0.4rem;">
					<button class="btn" tapmode onclick="reg()" id="login-btn">校验信息</button>
				</li>
			</ul>
		</div>
		<!--完善信息end-->
	
	</body>
	<script type="text/javascript" src="../../script/api.js"></script>
	<script type="text/javascript" src="../../script/app.js"></script>
	<script type="text/javascript" src="../../script/md5.js"></script>
	<script type="text/javascript">
		var mobile = '';
		var password = '';
		var imgs = [];
		var idcardfrom = '';
		var idcardaddr = '';
		var idcarddate = '';
		var UIInput;
		var keyboardId = 0;//当前键盘ID
		var easeChat;
		apiready = function() {
			api.parseTapmode();
			mobile = api.pageParam.mobile;
			password = api.pageParam.password;
			UIInput = api.require('UIInput');
			//fnInitUIInput();
			easeChat = api.require('easeChat');
		}
		function selpic(id) {
			api.actionSheet({
				cancelTitle: '取消',
				buttons: ['拍照', '从手机相册选择'],
				style: {
					layerColor:'rgba(0,0,0,0.3)',         //遮蔽层颜色，仅支持 rgba颜色，默认值：rgba（0, 0, 0, 0.4）
					itemNormalColor:'#fff',    //选项按钮正常状态背景颜色，支持#000、#000000、rgb、rgba，默认值：#F1F1F1
					itemPressColor:'#f5f5f5',     //选项按钮按下时背景颜色，支持#000、#000000、rgb、rgba，默认值：#E6E6E6
					fontNormalColor:'#333',    //选项按钮正常状态文字颜色，支持#000、#000000、rgb、rgba，默认值：#007AFF
					fontPressColor:'#000',     //选项按钮按下时文字颜色，支持#000、#000000、rgb、rgba，默认值：#0060F0
					titleFontColor:'#000'      //标题文字颜色，支持#000、#000000、rgb、rgba，默认值：#8F8F8F
				}
			}, function(ret, err) {
				if(ret.buttonIndex==1 || ret.buttonIndex==2)
				{
					getPicture(ret.buttonIndex,id);
				}
			});
		}
		function getPicture(index,id){
			var sourceType = 'library';
            if(index==1){
				sourceType = 'camera';
			}			
			api.getPicture({
				sourceType: sourceType,
				encodingType: 'png',
				mediaValue: 'pic',
				targetWidth: 600,
			}, function(ret, err) {
			// 获取图片数据并处理
				if (ret) {
					var imgSrc = ret.data;
					if (imgSrc != "") {
						uploadImage(imgSrc,id);
						if(id == 1)
						{
							getAiIDcard(imgSrc,'idcard');
						}
						else if(id == 2)
						{
							getAiIDcard(imgSrc,'idcardback');
						}
					}
				}
			});
		}
		function getAiIDcard(imgPath,cardside)
		{
			api.showProgress({
				title: '正在识别...',
				text: '',
				modal: true
			});
			//获取身份证信息
			var trans = api.require('trans');
			trans.decodeImgToBase64({
				imgPath: imgPath
			}, function(ret, err) {
				if (ret.status) {
					//转换成base64后上传
					var paramsObj = {
						app_key: kAppKey,
						type: cardside
					}
					var _sign = getSign(paramsObj, kAppKey, kAppSecret);
					paramsObj.base64str = 'data:image/jpeg;base64,'+ret.base64Str;
					paramsObj.signature = _sign;
					//console.log(JSON.stringify(paramsObj)+'!!!!!!');
					api.ajax({
						url: ApiUrl + '/v1/aips',
						method: 'post',
						data: {
							values: paramsObj
						}
					}, function(ret, err) {
						api.hideProgress();
						if (ret) {
							//alert(JSON.stringify(ret));
							if(cardside == 'idcard')
							{
								var idcard = '';
								var realname = '';
								for(var index in ret.words_result)
								{
									if(index == '公民身份号码')
									{
										idcard = ret.words_result[index].words;
									}
									else if(index == '姓名')
									{
										realname = ret.words_result[index].words;
									}
									else if(index == '住址')
									{
										idcardaddr = ret.words_result[index].words;
									}
									else if(index == '签发日期')
									{
										idcarddate = ret.words_result[index].words;
									}
									else if(index == '签发机关')
									{
										idcardfrom = ret.words_result[index].words;
									}
									//alert(index+'?'+JSON.stringify(ret.words_result[index]));
								}
								$api.val($api.byId('realname'),realname);
								$api.val($api.byId('idcard'),idcard);
							}
							else
							{
								for(var index in ret.words_result)
								{
									if(index == '签发日期')
									{
										idcarddate = ret.words_result[index].words;
									}
									else if(index == '签发机关')
									{
										idcardfrom = ret.words_result[index].words;
									}
									//alert(index+'?'+JSON.stringify(ret.words_result[index]));
								}
							}
						} else {
							console.log(JSON.stringify(err));
							toast(err.body.message);
						}
						
					});
				}
			});
		}
		function uploadImage(item,id)
		{
			var imageCachePath = api.cacheDir;
			var picname = randomString(32);
			//imgFilter(item,id);
			
			if(api.systemType != 'ios'){
				imgFilter(item,id);
			}
			else
			{
				imgFilter(item,id);
			}
		}
		function randomString(len) {
		　　len = len || 32;
		　　var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
		　　var maxPos = $chars.length;
		　　var pwd = '';
		　　for (i = 0; i < len; i++) {
		　　　　pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
		　　}
		　　return pwd;
		}
		function imgFilter(item,id) {
			console.log(item+'压缩前路径');
			//压缩图片
			var picname = randomString(32);
			var imageCachePath = api.cacheDir;
			var imageFilter = api.require('imageFilter');
			imageFilter.compress({
				img: item,
				quality : 1,
				scale : 1,
				save : {
					album : false,
					imgPath : imageCachePath,
					imgName : picname + '.jpg'
				}
			},function( ret, err ){        
				if( ret.status ){
					//$api.attr($api.byId('cardIDthumb'+id),'src',imageCachePath + '/' + picname + '.jpg');
					$api.byId('cardIDthumb'+id).src = imageCachePath + '/' + picname + '.jpg';
					imgs = [];
					for (var i = 1; i < parseInt(id)+1; i++) {
						var picurl = $api.attr($api.byId('cardIDthumb'+i),'src');
						var trans = api.require('trans');
						trans.decodeImgToBase64({
							imgPath: picurl
						}, function(ret, err) {
							if (ret.status) {
								//转换成base64后上传
								imgs.push('data:image/jpeg;base64,'+ret.base64Str);
							}
						});
					}
					//postfile(imageCachePath + '/' + picname + '.jpg');
					//arrpic.push(imageCachePath + '/' + picname + '.jpg');

				}else{
					alert( JSON.stringify( err ) );
				}
			});
		}
		function reg() {
			//hideInput();//收起键盘
			var realname = $api.val($api.byId('realname')).trim();
			var cardID = $api.val($api.byId('idcard')).trim();
			if($api.cssVal($api.byId('login-btn'),'opacity')!=1)
			{
				return false;
			}
			
			if(imgs.length < 3)
			{
				toast("请上传身份证照片");
				return false;
			}
			if(realname == '')
			{
				toast("请填写姓名");
				return false;
			}
			if(cardID == '')
			{
				toast("请填写身份证号码");
				return false;
			}
			if(!IdentityCodeValid(cardID))
			{
				toast("请填写真实身份证号码");
				return false;
			}
			showbtnloading('login-btn');
			var paramsObj = {
				app_key: kAppKey,
				mobile: mobile,
				password: password,
				realname: realname,
				idcard: cardID,
				regtype: 3,
				idcardfrom: idcardfrom,
				idcardaddr: idcardaddr,
				idcarddate: idcarddate
			}
			var _sign = getSign(paramsObj, kAppKey, kAppSecret);
			paramsObj.base64str = imgs;
			paramsObj.signature = _sign;
			//console.log(JSON.stringify(paramsObj)+'!!!!!!');
			api.ajax({
				url: ApiUrl + '/v1/token/reg',
				method: 'post',
				data: {
					values: paramsObj
				}
			}, function(ret, err) {
				if (ret) {
					easeChat.login({
					   username: 'shipper_'+mobile,
					   password: mobile.substring(mobile.length-6),
					   autoLogin: true
					},function(ret, err) {
						if (ret.status) {
							//api.alert({ msg:'登录成功'});
						} else {
							//api.alert({ msg:'登录失败，可能无法收到消息！'});
						}
					});
					//保存融云token
					var access_token = ret.data.access_token;
					//var rongcloud_token = ret.data.client.rongcloud_token;
					var credit = ret.data.client.credit;
					var userjson = {
						access_token : access_token,
						uid: ret.data.client.uid,
						realname: ret.data.client.realname,
						credit: credit,
						avatar: ret.data.client.avatar,
						mobile: ret.data.client.mobile,
						status: ret.data.client.status,
						email: ret.data.client.email,
						address: ret.data.client.address,
						companyId: ret.data.client.companyId,
						sparestatus: ret.data.client.sparestatus,
						bindqq: ret.data.client.bindqq,
						bindwx: ret.data.client.bindwx,
						bindweibo: ret.data.client.bindweibo
					};
					api.setPrefs({
						key: 'user_info',
						value: userjson
					}, function(ret, err) {
						//closeWin();
					});
					api.execScript({
						name: 'root',
						script: 'inithuanxin(\''+userjson.uid+'\');'
					});
					api.sendEvent({
						name : 'updateuser',
						extra : {
							userjson : userjson
						}
					});
					//checkface(ret.data.client.uid,cardID,realname);
					checkface(ret.data.client.uid,ret.data.client.cardIDthumb3);
				} else {
					console.log(JSON.stringify(err));
					toast(err.body.message);
				}
				hidebtnloading('login-btn','校验信息');
			});
		}
		function checkface(uid,cardIDthumb) {
			//人脸识别
			var demo = api.require('baiduFaceLive');
			demo.openFaceDetectView(function(ret, err){
				if(ret.evenType=='success'){
					//由于base64数据量大，请不要用JSON.stringify(ret)调试
					var paramsObj = {
						app_key: kAppKey,
						type: 'addface',
						uid: uid,
						cardIDthumb: cardIDthumb
						//idcard: idcard,
						//realname: realname
					}
					var _sign = getSign(paramsObj, kAppKey, kAppSecret);
					paramsObj.base64str = 'data:image/jpeg;base64,'+ret.data.bestImage;
					paramsObj.signature = _sign;
					//console.log(JSON.stringify(paramsObj)+'!!!!!!');
					api.ajax({
						url: ApiUrl + '/v1/aips',
						method: 'post',
						data: {
							values: paramsObj
						}
					}, function(ret, err) {
						if (ret) {
							console.log(JSON.stringify(ret));
							openAlert('success');
						} else {
							//验证失败，退出无法登陆
							api.removePrefs({
								key: 'user_info'
							});
							var userjson = {};
							var usersetting = 'updateuser('+ JSON.stringify(userjson) +');';
							console.log(JSON.stringify(err));
							//toast(err.body.message);
							openAlert('fail');
						}
						demo.closeFaceDetectView(function(ret, err){
							//alert(JSON.stringify(ret));
						});
					});
					
					
					
					
				}else{
					//api.toast({ msg : JSON.stringify(ret) +"  "+JSON.stringify(err)});
				}
			});
		}
		function openAlert(type)
		{
			var icon = 'info.png';
			var title = '人脸识别校验失败';
			var msg = '已转为人工审核，人工审核将于3个工作日内完成<br/>并将审核结果发送至您注册使用的手机号<br/>请留意查收';
			var winname = 'login_win';
			var btntxt = '返回登录';
			var changestyle = 0;
			if(type == 'success')
			{
				icon = 'suc.png';
				title = '身份信息认证成功';
				msg = '';
				winname = 'root';
				btntxt = '进入首页';
				changestyle = 1;
			}
			var param = {
				icon: icon,
				title: title,
				msg: msg,
				btntxt: btntxt,
				winname: winname,
				changestyle: changestyle
			};
			opWin('msg_win','../public/msg_win.html',false,param,false);
		}
		function hideInput(){
			//隐藏键盘
			$api.byId('realname').blur();
			$api.byId('cardID').blur();
			$api.byId('certCode').blur();
			$api.byId('workCode').blur();
			$api.byId('managermobile').blur();
			$api.byId('chargemobile').blur();
			//UIInput.closeKeyboard({
				//id: keyboardId
			//});
		}
		function fnInitUIInput(){
			//计算位置
			openUIinput('mobile','请输入您的手机号','number','text');
			openUIinput('vcode','请输入验证码','number','text');
		}
		function openUIinput(domid,placeholder_str,keyboardType,inputType){
			//打开UIinput
			var password = $api.byId(domid);
			var password_rect = $api.offset(password);
			UIInput.open({
				rect: {
					x: password_rect.l,
					y: password_rect.t,
					w: password_rect.w,
					h: password_rect.h -1
				},
				styles: {
					bgColor: '#fff',
					size: 13,
					color: '#000',
					placeholder: {
						color: '#999'
					}
				},
				autoFocus: false,
				maxRows: 1,
				placeholder: placeholder_str,
				keyboardType: keyboardType,
				inputType: inputType,
				fixedOn: api.frameName,
				fixed: false
			}, function(ret) {
				
				if (ret.eventType == 'change') {
					keyboardId = ret.id;
					UIInput.value({
							id: ret.id,
							//msg : '设置输入框的值'
					}, function(ret, err) {
						if (ret) {
							$api.val(password,ret.msg);
						} else {
							//alert(JSON.stringify(err));
						}
					});
				} else {
					//alert(JSON.stringify(ret));
				}
			});
			
		}
		function IdentityCodeValid(code) { 
			var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
            var tip = "";
            var pass= true;

            if(!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)){
                tip = "身份证号格式错误";
                pass = false;
            }

			else if(!city[code.substr(0,2)]){
                tip = "地址编码错误";
                pass = false;
            }
            else{
                //18位身份证需要验证最后一位校验位
                if(code.length == 18){
                    code = code.split('');
                    //∑(ai×Wi)(mod 11)
                    //加权因子
                    var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
                    //校验位
                    var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
                    var sum = 0;
                    var ai = 0;
                    var wi = 0;
                    for (var i = 0; i < 17; i++)
                    {
                        ai = code[i];
                        wi = factor[i];
                        sum += ai * wi;
                    }
                    var last = parity[sum % 11];
                    if(parity[sum % 11] != code[17]){
                        tip = "校验位错误";
                        pass =false;
                    }
                }
            }
            //if(!pass) alert(tip);
            return pass;
        }
		function closeWin(){
			api.closeWin({
			});
		}
	</script>
</html>